package com.duothread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo4 {
    public static void main(String[] args) {
        SellTicketTask task = new SellTicketTask();
        Thread thread1 = new Thread(task, "窗口1");
        Thread thread2 = new Thread(task, "窗口2");
        Thread thread3 = new Thread(task, "窗口3");
        Thread thread4 = new Thread(task, "窗口4");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
}

class SellTicketTask implements Runnable {
    private int tickets = 100;
    // 定义一把锁
    Lock l = new ReentrantLock();

    @Override

    public void run() {
        while (true) {
            // 加锁
            l.lock();

            if (tickets > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + "出票：" + tickets);
                tickets--;
            } else {
                break;
            }

            // 释放锁
            l.unlock();
        }
    }
}